<?php

namespace common\observer;

use Webman\Stomp\Client;
use common\model\TaskModel;
use support\SingletonTrait;
use common\model\EntityModel;
use common\model\OrderTaskListModel;
use common\service\TaskUpstreamService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 镜头新增关联序列
 */
class ShotAddSequenceRelationHandle implements SplObserver
{
    use SingletonTrait;

    /**
     * @param SplSubject $subject
     * @return void
     * @throws \think\Exception
     */
    public function update(SplSubject $subject): void
    {
        $entity = $subject->getSubjectData();
        $updateData = $subject->getSplUpdateData();

        $currentModule = module_by_id($entity['module_id']);
        if (empty($currentModule) || $currentModule['code'] != 'shot') {
            return;
        }
        $changedKey = array_keys($updateData);
        if (!in_array('entity_id', $changedKey) || $updateData['entity_id'] <= 0) {
            return;
        }
        try {
            $this->sequenceDownstreamTaskOutsideExecuteRegenerateTaskFileList($subject);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }

    /**
     * 序列下游外包出去的任务  重新生成订单文件列表
     * @param $subject
     * @return void
     */
    private function sequenceDownstreamTaskOutsideExecuteRegenerateTaskFileList($subject)
    {

        $updateData = $subject->getSplUpdateData();
        $sequence = model(EntityModel::class)->find($updateData['entity_id']);
        $sequenceTaskList = model(TaskModel::class)->where(['entity_id' => $updateData['entity_id'], 'step_type' => TaskModel::STEP_TYPE_STEP])->select();

        $sendOutTaskList = [];
        foreach ($sequenceTaskList as $task) {
            $downstreamTaskList = TaskUpstreamService::getInstance()->getDownstreamTaskList($task['id']);
            $downstreamTaskList = array_filter($downstreamTaskList, function ($item) {
                return in_array($item['executor_type'], TaskModel::OUTSIDE_EXECUTE_TYPE_GROUP);
            });
            foreach ($downstreamTaskList as $downstreamTask) {
                $sendOutTaskList[] = $downstreamTask;
            }
        }

        if (empty($sendOutTaskList)) {
            return;
        }

        $orderIdList = model(OrderTaskListModel::class)
            ->where(['task_id' => ['IN', array_column($sendOutTaskList, 'id')]])
            ->group('order_id')
            ->field('order_id')
            ->select();
        $orderIdList = array_column($orderIdList, 'order_id');

        foreach ($orderIdList as $orderId) {
            Client::send('generate_order_task_file_list', build_queue_data_with_xu(['order_id' => $orderId, 'user_id' => request()->getUserId()]));
        }
    }
}
